<!-- tinymc富文本 -->
<template>
  <div>
    <editor
      v-model="myValue"
      :init="init"
      :disabled="disabled"
      @onClick="onClick"
    >
    </editor>
  </div>
</template>

<script>
/* eslint-disable */
import tinymce from 'tinymce/tinymce' // eslint-disable-next-line
import Editor from '@tinymce/tinymce-vue' // eslint-disable-next-line
import 'tinymce/skins/ui/oxide/skin.css'
import '../../assets/tinymce/langs/zh_CN' // 本地汉化
import 'tinymce/themes/silver/theme'
// 引入所有你用得到的插件（根据 tinymce/plugins 目录）
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/anchor'
import 'tinymce/plugins/autolink'
import 'tinymce/plugins/autoresize'
import 'tinymce/plugins/autosave'
import 'tinymce/plugins/charmap'
import 'tinymce/plugins/code'
import 'tinymce/plugins/codesample'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/contextmenu'
import 'tinymce/plugins/directionality'
import 'tinymce/plugins/emoticons'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/help'
import 'tinymce/plugins/hr'
import 'tinymce/plugins/image'
import 'tinymce/plugins/imagetools'
import 'tinymce/plugins/importcss'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/link'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/media'
import 'tinymce/plugins/nonbreaking'
import 'tinymce/plugins/pagebreak'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/print'
import 'tinymce/plugins/save'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/spellchecker'
import 'tinymce/plugins/tabfocus'
import 'tinymce/plugins/table'
import 'tinymce/plugins/template'
import 'tinymce/plugins/textcolor'
import 'tinymce/plugins/visualblocks'
import 'tinymce/plugins/visualchars'
import 'tinymce/plugins/wordcount'
// 如果你有本地插件，也可以在这里一起 import

import 'tinymce/icons/default'

export default {
  name: 'tinymce',
  components: {
    Editor
  },
  props: {
    //传入一个value，使组件支持v-model绑定
    value: {
      type: String,
      default: ''
    },
    height: {
      type: Number,
      default: 500
    },

    disabled: {
      type: Boolean,
      default: false
    },
    plugins: {
      type: [String, Array],
      // default: ['link', 'image', 'table', 'code', 'fullscreen', 'wordcount']
      default:
        ' anchor autolink code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image media imagetools insertdatetime link lists noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
      // 'lists image media table  wordcount '
    },
    toolbar: {
      type: [String, Array],
      default:
        // 'undo redo | searchreplace | bold  italic | underline | strikethrough | alignleft  aligncenter alignright | outdent indent  blockquote  removeformat subscript superscript code codesample hr bullist numlist link image charmap preview anchor pagebreak insertdatetime  table  forecolor backcolor'
        'undo redo |  formatselect insertHTML | lists image media  | removeformat hr | code bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent '
    }
  },
  data() {
    return {
      //初始化配置
      init: {
        valid_elements: '*[*]', // 允许所有标签所有属性
        extended_valid_elements: '*[*]', // 扩展支持
        language_url: '../../assets/tinymce/langs/zh_CN', // 这里需要单独处理
        language: 'zh_CN',
        height: this.height,
        // width: this.width,
        plugins: this.plugins,
        toolbar: this.toolbar,
        branding: true,
        menubar: true,
        autosave_ask_before_unload: false, // 禁用自动保存
        image_dimensions: false, // 取消图片设置大小
        //此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
        //如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
        images_upload_handler: (blobInfo, success, failure) => {
          const blob = blobInfo.blob()
          const blobUrl = URL.createObjectURL(blob)
          // 你自己的上传逻辑...
          // success('image_url.jpg', {width: '50%'});
          success(blobUrl)

          // const blobUrl = URL.createObjectURL(blob)

          // const base64 = 'data:image/jpeg;base64,' + blobInfo.base64()

          // // 避免重复添加
          // if (!this.tempFileList.find((img) => img.base64 === base64)) {
          //   this.tempFileList.push({
          //     base64,
          //     blob: blobInfo.blob()
          //   })
          // }

          // success(base64)
        },
        // style_formats: [
        //   {
        //     title: 'Image Left',
        //     selector: 'img',
        //     styles: {
        //       float: 'left',
        //       margin: '0 10px 0 10px'
        //     }
        //   },
        //   {
        //     title: 'Image Right',
        //     selector: 'img',
        //     styles: {
        //       float: 'right',
        //       margin: '0 10px 0 10px'
        //     }
        //   }
        // ],
        resize: true,
        setup(editor) {
          editor.on('BeforeSetContent', function (e) {
            if (e.content.includes('<img')) {
              e.content = e.content.replace(
                /<img /g,
                '<img style="width:100%;display: block; height: auto;" '
              )
            }
          })
          editor.ui.registry.addButton('insertHTML', {
            text: 'HTML',
            onAction: function () {
              // 弹出内置弹窗
              editor.windowManager.open({
                title: '插入HTML片段',
                minWidth: 500,
                body: {
                  type: 'panel',
                  items: [
                    {
                      type: 'textarea',
                      name: 'html',
                      label: 'HTML 内容',
                      height: 600
                    }
                  ]
                },
                buttons: [
                  {
                    type: 'cancel',
                    text: '取消'
                  },
                  {
                    type: 'submit',
                    text: '插入',
                    primary: true
                  }
                ],
                onSubmit(api) {
                  const data = api.getData()
                  editor.insertContent(data.html)
                  api.close()
                }
              })
            }
          })
        }
      },
      myValue: this.value
    }
  },
  mounted() {
    tinymce.init({})
  },
  methods: {
    //添加相关的事件，可用的事件参照文档=> https://github.com/tinymce/tinymce-vue => All available events
    //需要什么事件可以自己增加
    onClick(e) {
      this.$emit('onClick', e, tinymce)
    },
    clear() {
      this.myValue = ''
    }
  },
  watch: {
    value(newValue) {
      this.myValue = newValue
    },
    myValue(newValue) {
      this.$emit('input', newValue)
    }
  }
}
</script>
<style scoped></style>
